package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.ResultCode;
import com.example.entity.Activity;
import com.example.exception.BusinessException;
import com.example.mapper.ActivityMapper;
import com.example.service.ActivityService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    @Override
    public Page<Activity> getActivityList(Integer pageNum, Integer pageSize, String keyword, Integer status) {
        Page<Activity> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.like(Activity::getTitle, keyword)
                    .or()
                    .like(Activity::getDescription, keyword)
                    .or()
                    .like(Activity::getLocation, keyword);
        }
        
        // 状态筛选
        if (status != null) {
            wrapper.eq(Activity::getStatus, status);
        }
        
        wrapper.orderByDesc(Activity::getCreateTime);
        return page(page, wrapper);
    }

    @Override
    @Transactional
    public boolean publishActivity(Activity activity) {
        // 设置初始状态为待审核
        activity.setStatus(0);
        // 设置初始报名人数为0
        activity.setSignupCount(0);
        
        // 检查时间是否合法
        if (activity.getStartTime().isBefore(LocalDateTime.now())) {
            throw new BusinessException("活动开始时间不能早于当前时间");
        }
        if (activity.getEndTime().isBefore(activity.getStartTime())) {
            throw new BusinessException("活动结束时间不能早于开始时间");
        }
        
        return save(activity);
    }

    @Override
    @Transactional
    public boolean updateActivity(Activity activity) {
        // 检查活动是否存在
        Activity existingActivity = getById(activity.getId());
        if (existingActivity == null) {
            throw new BusinessException(ResultCode.ACTIVITY_NOT_FOUND);
        }
        
        // 检查活动状态是否允许修改
        if (existingActivity.getStatus() != 0 && existingActivity.getStatus() != 1) {
            throw new BusinessException("当前活动状态不允许修改");
        }
        
        // 检查时间是否合法
        if (activity.getStartTime().isBefore(LocalDateTime.now())) {
            throw new BusinessException("活动开始时间不能早于当前时间");
        }
        if (activity.getEndTime().isBefore(activity.getStartTime())) {
            throw new BusinessException("活动结束时间不能早于开始时间");
        }
        
        return updateById(activity);
    }

    @Override
    @Transactional
    public boolean deleteActivity(Long id) {
        // 检查活动是否存在
        Activity activity = getById(id);
        if (activity == null) {
            throw new BusinessException(ResultCode.ACTIVITY_NOT_FOUND);
        }
        
        // 检查活动状态是否允许删除
        if (activity.getStatus() == 1) {
            throw new BusinessException("进行中的活动不能删除");
        }
        
        return removeById(id);
    }

    @Override
    @Transactional
    public boolean batchDeleteActivities(Long[] ids) {
        // 检查所有活动是否存在且可删除
        for (Long id : ids) {
            Activity activity = getById(id);
            if (activity == null) {
                throw new BusinessException(ResultCode.ACTIVITY_NOT_FOUND);
            }
            if (activity.getStatus() == 1) {
                throw new BusinessException("进行中的活动不能删除");
            }
        }
        
        return removeByIds(Arrays.asList(ids));
    }

    @Override
    @Transactional
    public boolean updateActivityStatus(Long id, Integer status) {
        // 检查活动是否存在
        Activity activity = getById(id);
        if (activity == null) {
            throw new BusinessException(ResultCode.ACTIVITY_NOT_FOUND);
        }
        
        // 检查状态值是否合法
        if (status < 0 || status > 3) {
            throw new BusinessException("状态值不合法");
        }
        
        // 检查状态流转是否合法
        if (!isValidStatusTransition(activity.getStatus(), status)) {
            throw new BusinessException("非法的状态变更");
        }
        
        Activity updateActivity = new Activity();
        updateActivity.setId(id);
        updateActivity.setStatus(status);
        return updateById(updateActivity);
    }

    @Override
    public Activity getActivityInfo(Long id) {
        Activity activity = getById(id);
        if (activity == null) {
            throw new BusinessException(ResultCode.ACTIVITY_NOT_FOUND);
        }
        return activity;
    }
    
    // 检查状态流转是否合法
    private boolean isValidStatusTransition(Integer currentStatus, Integer newStatus) {
        // 待审核 -> 进行中/已取消
        if (currentStatus == 0 && (newStatus == 1 || newStatus == 3)) {
            return true;
        }
        // 进行中 -> 已结束/已取消
        if (currentStatus == 1 && (newStatus == 2 || newStatus == 3)) {
            return true;
        }
        // 其他状态不允许变更
        return false;
    }
} 